﻿using AppService.IService.System_setting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.IdentityModel.Tokens.Jwt;

namespace TMS_BackEnd.Filters
{
    public class HelperFilter : IAuthorizationFilter
    {

        public HelperFilter(IEmployeeService employeeService)
        {
            this.employeeService = employeeService;
        }

        public IEmployeeService employeeService { get; set; }
        
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            string token = context.HttpContext.Request.Headers["Authorization"];
            string tokenStr = token.Replace("Bearer ", "");
            var handler = new JwtSecurityTokenHandler();
            var payload = handler.ReadJwtToken(tokenStr).Payload;
            var claims = payload.Claims;
            var Id = claims.First(claims => claims.Value != "").Value;
            if (!employeeService.IsEmpId(Convert.ToInt32(Id)))
            {
                context.Result = new JsonResult(new
                {
                    code = -1,
                    message = "验证失败"
                });
            }
        }
    }
}
